import OperationCol from '@/components/OperationCol'
import SealStatus, { statusList } from '@/components/SealStatus'
import payOrder from '@/lib/request/payOrder'
import {
  adminTypes,
  formatStatus,
  orgLicenseTypes,
  orgTypes,
  useTypes,
  userLicenseTypes,
  sealTypes,
  orderStatusList,
  statusColor,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import { RootState } from '@/store'
import { Component, Vue } from 'vue-property-decorator'
import { Action, Mutation, State } from 'vuex-class'
import { UserState } from '@/store/modules/user'
// import ApplyDetail from "./ApplyDetail";
import ApplyInvoice from './ApplyInvoice'
import styles from './NewApply.less'
import operationStyles from '@/components/OperationCol.less'
import { getTimeline } from '@/lib/sealFormat'
import { Table } from 'element-ui'
import RefundDialog from '@/views/NewApply/refundDialog'
import TableEmpty from '@/components/tableEmpty'

export const uploadUrl = '/seal/rest/file/uploadPicMulti'

@Component({})
export default class NewApply extends Vue {
  @State((state: RootState) => state.newApply.sealList)
  private sealList!: any[]
  @State((state: RootState) => state.newApply.total)
  private total!: number
  @State((state: RootState) => state.newApply.applyVisible)
  private applyVisible!: boolean
  @State((state: RootState) => state.newApply.detailVisible)
  private detailVisible!: boolean
  @State((state: RootState) => state.newApply.loading)
  private loading!: boolean
  @State((state: RootState) => state.newApply.orgList)
  private orgList!: any[]
  @State((state: RootState) => state.newApply.auditOrgList)
  private auditOrgList!: any[]
  @State((state: RootState) => state.newApply.applyData)
  private applyData!: any
  @State((state: RootState) => state.user)
  private user!: UserState
  @State((state: RootState) => state.newApply.applyInvoiceVisible)
  private applyInvoiceVisible!: boolean
  @State((state: RootState) => state.newApply.applyInvoiceData)
  private applyInvoiceData!: any

  private sealType: number[] = []
  private status: number[] = []
  private sealName: string = ''
  private pageIndex: number = 1
  private pageSize: number = 10
  private applyTitle: string = '印章申请'
  private showTimeline: boolean = false
  private saveLoading: boolean = false
  private sealOption: any[] = []
  private sealApplyId = ''
  private disabledRefundBtn: boolean = false

  @State((state: RootState) => state.newApply.refundDialogVisible)
  private refundDialogVisible!: boolean
  @State((state: RootState) => state.newApply.refundData)
  private refundData!: any

  @Mutation('newApply/setStateData') private setStateData!: (data: any) => {}
  @Action('newApply/getList') private getList!: any
  @Action('newApply/queryOrg') private queryOrg!: any
  @Action('newApply/queryAuditOrg') private queryAuditOrg!: any
  @Action('newApply/saveSeal') private saveSeal!: any
  @Action('newApply/saveAndSubmit') private saveAndSubmit!: any
  @Action('newApply/submitSeal') private submitSeal!: any
  @Action('newApply/sealDetail') private sealDetail!: any
  @Action('newApply/deleteApply') private deleteApply!: any
  @Action('newApply/sealRecall') private sealRecall!: any
  @Action('newApply/sealRefund') private sealRefund!: any
  @Action('newApply/receiptConfirm') private receiptConfirm!: any
  @Action('paymentOrder/queryByOrderId') private queryByOrderId!: any

  protected render() {
    return (
      <div class="p10">
        <div class={{ [styles.query]: true, custom: true }}>
          <span class={styles.part}>
            <span>印章类别</span>
            <el-select
              v-model={this.sealType}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {sealTypes.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.id}
                  label={sealType.value}
                  value={sealType.id}
                />
              ))}
            </el-select>
          </span>
          <span class={styles.part}>
            <span>申请状态</span>
            <el-select
              v-model={this.status}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {this.statusArry.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.key}
                  label={sealType.text}
                  value={sealType.key}
                />
              ))}
            </el-select>
          </span>
          <span class={styles.part}>
            <span>申请编号</span>
            <el-input v-model={this.sealApplyId} />
          </span>
          <span class={styles.part}>
            <span>印章名称</span>
            <el-input v-model={this.sealName} />
          </span>
          <span class={styles.part}>
            <el-button
              onClick={this.query}
              loading={this.loading}
              plain
              class="min color-blue"
            >
              搜索
            </el-button>
            <el-button onClick={this.reset} plain class="min color-gray">
              重置
            </el-button>
          </span>
        </div>
        <p class="pt5">
          <el-button class="medium bg-color-blue" onClick={this.applySeal}>
            申请印章
          </el-button>
        </p>
        <el-table
          data={this.sealList}
          style="width: 100%"
          v-loading={this.loading}
          ref="table"
        >
          <TableEmpty
            v-show={!this.loading}
            slot="empty"
            msg="暂无匹配的印章申请记录"
            url={require('@/assets/seal-empty.svg')}
          >
            <el-button type="primary" onClick={this.applySeal}>
              前往申请印章
            </el-button>
          </TableEmpty>
          <el-table-column
            prop="sealApplyRecordId"
            label="申请编号"
            min-width="160"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealName"
            label="印章名称"
            min-width="160"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealType"
            label="印章类别"
            min-width="80"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return formatStatus(sealTypes, scope.row.sealType)
                },
              },
            }}
          />
          <el-table-column
            prop="organizeName"
            label="用章机构名称"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealApplyStatus"
            label="状态"
            min-width="120"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return <SealStatus status={scope.row.sealApplyStatus} />
                },
              },
            }}
          />

          <el-table-column
            prop="id"
            label="操作"
            width="265"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <OperationCol
                      operations={this.filterOpera(scope.row)}
                      showNum={4}
                      row={scope.row}
                      index={scope.$index}
                    />
                  )
                },
              },
            }}
          />
        </el-table>
        {this.sealList && this.sealList.length > 0 && (
          <el-pagination
            class={{ [styles.pagination]: true }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pageIndex}
            page-sizes={[10, 20, 30]}
            page-size={this.pageSize}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.total}
            pager-count={5}
            // hide-on-single-page
          />
        )}
        {/* <ApplyDetail
          onVisibleChange={(val: boolean) => {
            this.setStateData({ detailVisible: val });
          }}
          visible={this.detailVisible}
          defaultData={this.applyData}
          sealOption={this.sealOption}
        /> */}
        <ApplyInvoice
          visible={this.applyInvoiceVisible}
          defaultData={this.applyInvoiceData}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ applyInvoiceVisible: val })
          }}
          onSubmitHandler={() => {
            this.query()
          }}
        />
        <RefundDialog
          visible={this.refundDialogVisible}
          defaultData={this.refundData}
          type="newApply"
          disabled={this.disabledRefundBtn}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ refundDialogVisible: val })
          }}
          onSubmit={this.confirmRefund}
        />
      </div>
    )
  }

  private mounted() {
    this.sealApplyId = this.$route.query.id as string
    this.query()
    if (this.sealApplyId) {
      this.$router.replace({ name: 'newApply' })
    }
  }

  get statusArry() {
    return statusList.filter(
      (item: any) =>
        item.key !== 6 &&
        item.key !== 9 &&
        item.key !== 10 &&
        item.key !== 24 &&
        item.key !== 25
    )
  }

  get agentInfo() {
    return {
      agentName: this.user.accountName,
      agentId: this.user.accountUUID,
      agentMobile: this.user.accountMobile,
      agentLicenseType: this.user.accountLicenseType,
      agentLicenseNumber: this.user.accountLicenseNumber,
      organizeName: this.user.organizeName,
      organizeUUID: this.user.organizeUUID,
      organizeType: this.user.organizeType,
      organizeAdministrationLevel: this.user.organizeAdministrationLevel,
      organizeLicenseType: this.user.organizeLicenseType,
      organizeLicenseNumber: this.user.organizeLicenseNumber,
      agentLicenseNumberDes: desensitization(
        this.user.accountLicenseNumber || ''
      ),
      agentMobileDes: desensitization(this.user.accountMobile || ''),
      sealName: this.user.organizeName,
    }
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 0,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.$router.push({
            name: 'applyFlow',
            params: { type: 'newApply' },
            query: { id: rows.sealApplyId, payType: rows.payType },
          })
        },
      },
      {
        id: 1,
        text: '删除',
        isDelete: true,
        onClick: (index: number, rows: any) => {
          this.delete(rows)
        },
      },
      {
        id: 2,
        text: '修改',
        onClick: (index: number, rows: any) => {
          this.update(rows)
        },
      },
      // {
      //   id: 3,
      //   text: "撤回",
      //   isDelete: true,
      //   customWarning: "撤回当前申请后无法恢复，是否继续？",
      //   onClick: (index: number, rows: any) => {
      //     this.resetApply(rows);
      //   }
      // },
      {
        id: 3,
        text: '撤回',
        onClick: (index: number, rows: any) => {
          this.refund(rows)
        },
      },
      {
        id: 4,
        text: '前往支付',
        onClick: (index: number, rows: any) => {
          this.toPay(rows)
        },
      },
      // {
      //   id: 5,
      //   text: "查看物流",
      //   isPopover: true,
      //   onClick: (index: number, rows: any) => {
      //     // this.takeOver(rows);
      //   },
      //   onHover: (index: number, rows: any) => {
      //     if (rows.sealUseType === 1) {
      //       this.queryByOrderInfo(rows)
      //     }

      //   },
      //   popoverContent: this.popoverRender
      // },
      {
        id: 5,
        text: '查看关联订单',
        onClick: (index: number, rows: any) => {
          this.$router.push({
            name: 'myOrderList',
            params: { type: 'all' },
            query: { orderNo: !!rows.orderNo ? rows.orderNo : undefined },
          })
        },
        hoverTips: '前往“我的订单”查看物流与下载发票',
      },
      {
        id: 6,
        text: '撤回',
        isDelete: true,
        onClick: (index: number, rows: any) => {
          this.resetApply(rows)
        },
      },
      // {
      //   id: 7,
      //   text: "开票详情",
      //   onClick: (index: number, rows: any) => {
      //     this.applyInvoiceHandler(rows);
      //   }
      // },
    ]

    return btns
  }

  private queryByOrderInfo(rows: any) {
    this.queryByOrderId(rows.payOrderId).then((res: any) => {
      const sealList = this.sealList.map(seal => {
        let info = {}
        if (seal.sealApplyId === rows.sealApplyId) {
          info = res
        }

        return {
          ...seal,
          ...info,
        }
      })
      this.setStateData({ sealList })
    })
  }

  private filterOpera(row: any) {
    const status = row.sealApplyStatus
    if (status === 1) {
      // 新增
      return [this.getOperations[1], this.getOperations[2]].concat(
        !!row.orderNo ? [this.getOperations[5]] : []
      )
    } else if (status === 2 || status === 3) {
      // 待审核、待制章
      return [this.getOperations[0], this.getOperations[3]].concat(
        !!row.orderNo ? [this.getOperations[5]] : []
      )
    } else if (status === 26) {
      // 待支付
      return [this.getOperations[4]]
    } else if (status === 90 || status === 91 || status === 92) {
      return [
        this.getOperations[0],
        this.getOperations[2],
        this.getOperations[3],
      ].concat(!!row.orderNo ? [this.getOperations[5]] : [])
    } else if (status === 93) {
      // 被统付方退回
      return [
        this.getOperations[0],
        this.getOperations[1],
        this.getOperations[2],
      ]
    } else if (status === 29) {
      // 待统付方审核
      return [this.getOperations[0], this.getOperations[6]]
    }

    return [this.getOperations[0]].concat(
      !!row.orderNo ? [this.getOperations[5]] : []
    )
  }

  private async query() {
    this.pageIndex = 1
    await this.queryList()
  }

  popoverRender(row: any) {
    return (
      <div class={operationStyles.popoverContent}>
        <p
          class={operationStyles.title}
          style={{ color: statusColor[row.sealApplyStatus] }}
        >
          <i class="el-icon-warning" />
          {orderStatusList[row.sealApplyStatus]}
        </p>
        {row.payType === 2 && row.sealUseType === 1 && (
          <p class={operationStyles.tips}>
            {
              '采用统一付费方式的UKey将会直接投递至统一付费方负责人地址请主动联络负责人领取'
            }
          </p>
        )}
        {row.sealUseType === 2 && (
          <p class={operationStyles.tips}>
            {'云签章支付成功后需要后台审核人员确认发货后才可正常使用。'}
          </p>
        )}
        {row.sealApplyStatus === 27 &&
          row.payType === 1 &&
          row.sealUseType === 1 && (
            <p class={operationStyles.tips}>
              如需修改收货地址请联络服务热线：4000878198转3(政务服务专线)
            </p>
          )}
        <p />
        {row.sealApplyStatus !== 27 && row.sealUseType === 1 && (
          <div class={operationStyles.logistics}>
            <div class={operationStyles.part}>
              <p class={operationStyles.title}>{row.logisticsCompany}：</p>
              <p class={operationStyles.content}>{row.logisticsNumber}</p>
            </div>
            <div class={operationStyles.part}>
              <p class={operationStyles.title}>发货时间：</p>
              <p class={operationStyles.content}>{row.deliveryTime}</p>
            </div>
            {row.confirmReceivingTime && (
              <div class={operationStyles.part}>
                <p class={operationStyles.title}>收货时间：</p>
                <p class={operationStyles.content}>
                  {row.confirmReceivingTime}
                </p>
              </div>
            )}
          </div>
        )}
        {row.sealApplyStatus !== 27 && row.sealUseType === 1 && (
          <div class={operationStyles.delivery}>
            <div class={operationStyles.part}>
              <p class={operationStyles.title}>收货人：</p>
              <p class={operationStyles.content}>{row.deliveryName}</p>
            </div>
            <div class={operationStyles.part}>
              <p class={operationStyles.title}>联系方式：</p>
              <p class={operationStyles.content}>
                {desensitization(row.deliveryMobile)}
              </p>
            </div>
            {row.postCode && (
              <div class={operationStyles.part}>
                <p class={operationStyles.title}>邮编：</p>
                <p class={operationStyles.content}>{row.postCode}</p>
              </div>
            )}
            <div class={operationStyles.part}>
              <p class={operationStyles.title}>收货地址：</p>
              <p class={operationStyles.content} title={row.deliveryAddress}>
                {row.deliveryAddress}
              </p>
            </div>
          </div>
        )}
        {row.sealApplyStatus === 28 && (
          <p class={operationStyles.opt}>
            <el-button
              type="text"
              onClick={() => {
                this.takeOver(row)
              }}
            >
              确认收货
            </el-button>
          </p>
        )}
      </div>
    )
  }

  private async queryList() {
    await this.getList(this)
    const table = this.$refs.table as Table
    table.doLayout()
  }

  private update(row: any) {
    this.$router.push({
      name: 'applyPage',
      params: { type: 'newApply' },
      query: { id: row.sealApplyId },
    })
  }

  private delete(row: any) {
    this.deleteApply(row.sealApplyId).then(() => {
      this.$message.success('删除成功')
      this.query()
    })
  }

  private refund(row: any) {
    this.setStateData({
      refundDialogVisible: true,
      refundData: row,
    })
  }

  private confirmRefund(data: any) {
    console.log({ ...data })
    this.disabledRefundBtn = true
    this.sealRefund({ ...data })
      .then((res: any) => {
        this.disabledRefundBtn = false
        this.$message.success('申请撤回成功')
        this.setStateData({
          refundDialogVisible: false,
        })
        this.query()
      })
      .catch((err: any) => {
        this.disabledRefundBtn = false
      })
  }

  private detail(row: any) {
    this.sealDetail(row.sealApplyId).then((data: any) => {
      this.setStateData({
        detailVisible: true,
        applyData: Object.assign({}, data, {
          agentLicenseType: formatStatus(
            userLicenseTypes,
            data.agentLicenseType
          ),
          applyOrganizeLevel: formatStatus(adminTypes, data.applyOrganizeLevel),
          applyOrganizeLicenseType: formatStatus(
            orgLicenseTypes,
            data.applyOrganizeLicenseType
          ),
          applyOrganizeType: formatStatus(orgTypes, data.applyOrganizeType),
          confirmOrganizeLicenseType: formatStatus(
            orgLicenseTypes,
            data.confirmOrganizeLicenseType
          ),
          sealType: formatStatus(sealTypes, data.sealType),
          sealUseType: formatStatus(useTypes, data.sealUseType),
          agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
          agentMobileDes: desensitization(data.agentMobile || ''),
          orderNo: data.orderNo,
        }),
      })
      this.sealOption = getTimeline(data.sealApplyStatus, this.applyData)
    })
  }

  private applyInvoiceHandler(row: any) {
    payOrder.queryPayOrderInfo(row.payOrderId).then(res => {
      console.log(res, 'res')
      res.data.payOrderId = row.payOrderId
      this.setStateData({
        applyInvoiceVisible: true,
        applyInvoiceData: {
          ...res.data,
          invoiceStatus: row.invoiceStatus,
          // invoiceStatus: 2
        },
      })
    })
  }

  private toPay(row: any) {
    if (!row.payOrderId) {
      //
      this.$router.push({
        name: 'applyPage',
        params: { type: 'newApply' },
        query: { id: row.sealApplyId, ic: 'true' },
      })
      // this.$router.push({ name: "paymentOrder", query: { id: row.sealApplyId }, params: { type: "newApply" } });
    } else {
      this.$router.push({
        name: 'orderConfirm',
        query: { orderId: row.payOrderId, sealApplyId: row.sealApplyId },
      })
    }
  }

  private takeOver(row: any) {
    this.receiptConfirm(row.sealApplyId).then(async (res: any) => {
      this.$message.success('已确认收货')
      await this.query()
      this.queryByOrderInfo(row) // 更新物流信息
    })
  }

  private createForm(sealData: any) {
    sessionStorage.setItem(
      'sealInfo',
      JSON.stringify({
        organize: sealData.organizeName,
        orgType: formatStatus(orgTypes, sealData.organizeType),
        licenseType: formatStatus(
          orgLicenseTypes,
          sealData.organizeLicenseType
        ),
        licenseNumber: sealData.organizeLicenseNumber,
        agentName: sealData.agentName,
        agentLicenseType: formatStatus(
          userLicenseTypes,
          sealData.agentLicenseType
        ),
        agentLicenseNumber: sealData.agentLicenseNumber,
        agentMobile: sealData.agentMobile,
        sealName: sealData.sealName,
        useType: formatStatus(useTypes, sealData.useType),
        auditOrg: sealData.auditOrganizeName,
      })
    )
    window.open(`${window.location.origin}/applyForm`, '_blank')
  }

  private submit(row: any) {
    this.submitSeal(row.sealApplyId).then((res: any) => {
      this.query()
    })
  }

  private handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  private handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  applySeal() {
    this.$router.push({
      name: 'applyPage',
      params: { type: this.$route.name || '' },
    })
  }

  private reset() {
    this.sealType = []
    this.status = []
    this.sealName = ''
    this.sealApplyId = ''
    this.query()
  }

  private async save(data: any) {
    this.saveLoading = true
    this.saveSeal(data)
      .then((res: any) => {
        this.saveLoading = false
        this.query()
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }

  private saveSubmit(data: any) {
    this.saveLoading = true
    this.saveAndSubmit(data)
      .then((res: any) => {
        this.saveLoading = false
        this.query()
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }

  private resetApply(row: any) {
    this.sealRecall(row.sealApplyId).then((res: any) => {
      this.query()
    })
  }
}
